/*
 * @Author: 泽斯
 * @Date: 2020-02-24
 * @Last Modified by: 泽斯
 * @Last Modified time: 2021-04-19
 * @desc 解析 excel => json && json => excel
 */
import XLSX from 'xlsx'

// 文件类型校验
function judgeFileType (name) {
  let fileType = name.split('.').pop()
  fileType = fileType.toLowerCase()
  return fileType === 'xlsx' || fileType === 'xls'
}

// excel to json
function analyzeExcel (sheet, cb) {
  let char, key
  const result = []
  const valueArr = new Set()
  if (sheet.A2) {
    char = 'A'
    key = 'phone'
  } else if (sheet.B2) {
    char = 'B'
    key = 'email'
  }
  for (const item in sheet) {
    if (item.indexOf(char) > -1) {
      const value = sheet[item].v.toString()
      if (value !== '手机号' && value !== '邮箱') {
        valueArr.add(value)
      }
    }
  }
  valueArr.forEach(item => {
    result.push({ [key]: item })
  })
  cb(result, key)
}


// 读取excel中内容
export default async function readExcel (file, cb) {
  if (!judgeFileType(file.name)) {
    const result = 'type error'
    cb(result) // eslint规定cb参数为变量
    return
  }
  const reader = new FileReader()
  // const name = file.name
  reader.onload = (e) => {
    const data = e.target.result
    const workbook = XLSX.read(data, { type: 'binary' })
    const sheetName = workbook.SheetNames[0]
    const sheet = workbook.Sheets[sheetName]
    console.log('read excel')
    console.log(sheet)
    // analyzeExcel(sheet)
    // if (isCoupon) {
    //   analyzeCoupon(sheet, cb)
    // } else {
    //   analyzeExcel(sheet, cb)
    // }
  }
  reader.readAsBinaryString(file)
}

let workBook = {
  SheetNames: [],
  Sheets: {},
  Props: {}
}

export function jsonToExcel (data) {
  workBook = {
    SheetNames: [],
    Sheets: {},
    Props: {}
  }
  const jsonDecrease = [] // 立减券
  const jsonProduct = [] // 产品体验券
  const jsonDs = [] // 加修加印券
  const jsonGiftCard = [] // 礼品卡
  const jsonInterior = [] // 开单折扣码
  const jsonPhysical = [] // 实体礼品卡
  data.map(item => {
    const obj = {
      券码类型: item.preferential_type,
      金额: item.money,
      code: item.code,
      券码使用限制: item.limit_description,
      生效时间: item.start_usage,
      失效时间: item.stop_usage
    }
    switch (item.preferential_type) {
    case '立减券': jsonDecrease.push(obj); break
    case '产品体验券': jsonProduct.push(obj); break
    case '加修加印券': jsonDs.push(obj); break
    case '虚拟礼品卡': jsonGiftCard.push(obj); break
    case '开单折扣码': jsonInterior.push(obj); break
    case '实体礼品卡': jsonPhysical.push(obj); break
    }
  })
  const filename = '券码.xlsx'
  if (jsonDecrease.length) {
    workBook.SheetNames.push('立减券')
    workBook.Sheets.立减券 = XLSX.utils.json_to_sheet(jsonDecrease)
  }
  if (jsonProduct.length) {
    workBook.SheetNames.push('产品体验券')
    workBook.Sheets.产品体验券 = XLSX.utils.json_to_sheet(jsonProduct)
  }
  if (jsonDs.length) {
    workBook.SheetNames.push('加修加印券')
    workBook.Sheets.加修加印券 = XLSX.utils.json_to_sheet(jsonDs)
  }
  if (jsonGiftCard.length) {
    workBook.SheetNames.push('虚拟礼品卡')
    workBook.Sheets.虚拟礼品卡 = XLSX.utils.json_to_sheet(jsonGiftCard)
  }
  if (jsonInterior.length) {
    workBook.SheetNames.push('开单折扣码')
    workBook.Sheets.开单折扣码 = XLSX.utils.json_to_sheet(jsonInterior)
  }
  if (jsonPhysical.length) {
    workBook.SheetNames.push('实体礼品卡')
    workBook.Sheets.实体礼品卡 = XLSX.utils.json_to_sheet(jsonPhysical)
  }
  XLSX.writeFile(workBook, filename)
}

function getCode (item, isAll) {
  if (item.type === 'interior_coupon') {
    return item.uuid
  }
  return (isAll ? item.code : item.white_list) || item.uuid
}

// 需要控制显示顺序，使用函数返回结果
function getCouponDetail (item, type, isAll = false) {
  if (type === 'whiteList') {
    const whiteListName = item.white_list.indexOf('@') > -1 ? '邮箱' : '手机号'
    return {
      [whiteListName]: item.white_list,
      是否绑定: item.is_get,
      是否使用: item.is_used || '',
      优惠券详情: item.preferential_info || '',
      门店: item.store || '',
      预约时间: item.reserve_time || '',
      订单号: item.order_no || ''
    }
  } else {
    return {
      券码: getCode(item, isAll),
      是否绑定: item.is_get,
      手机号: item.phone || '',
      是否使用: item.is_used || '',
      优惠券详情: item.preferential_info || '',
      门店: item.store || '',
      预约时间: item.reserve_time || '',
      订单号: item.order_no || ''
    }
  }
}

export function couponDetailToExcel (data, type, isAll) {
  let excel = {
    SheetNames: [],
    Sheets: {},
    Props: {}
  }
  const filename = '券码使用详情.xlsx'
  let result = []
  data.forEach(item => {
    result.push(getCouponDetail(item, type, isAll))
  })
  excel.SheetNames.push('使用详情')
  excel.Sheets.使用详情 = XLSX.utils.json_to_sheet(result)
  XLSX.writeFile(excel, filename)
}

export function couponDetailAllToExcel (data, type, isAll) {
  let excel = {
    SheetNames: [],
    Sheets: {},
    Props: {}
  }
  const filename = '券码使用详情.xlsx'
  let result = []
  const tableLists = []
  if (type === 'whiteList') {
    data.forEach(element => {
      if (element.preferential_use_info) {
        element.preferential_use_info.forEach(obj => {
          tableLists.push({
            white_list: element.white_list,
            is_get: element.is_get,
            is_used: obj.is_used,
            is_send: element.is_send,
            preferential_info: obj.preferential_info,
            store: obj.store,
            reserve_time: obj.reserve_time,
            order_no: obj.order_no
          })
        })
      } else {
        tableLists.push({
          white_list: element.white_list,
          is_get: element.is_get,
          is_used: '-',
          is_send: element.is_send,
          preferential_info: '-',
          store: '-',
          reserve_time: '-',
          order_no: '-'
        })
      }
    })
  } else {
    data.forEach(element => {
      tableLists.push({
        code: element.code,
        is_get: element.is_get,
        is_used: element.is_used,
        is_send: element.is_send,
        preferential_info: element.preferential_info,
        store: element.store,
        reserve_time: element.reserve_time,
        order_no: element.order_no,
        phone: element.phone,
        type: element.type,
        uuid: element.uuid
      })
    })
  }
  tableLists.forEach(item => {
    result.push(getCouponDetail(item, type, isAll))
  })
  excel.SheetNames.push('使用详情')
  excel.Sheets.使用详情 = XLSX.utils.json_to_sheet(result)
  XLSX.writeFile(excel, filename)
}
